package org.csu.mall.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.csu.mall.common.CONSTANT;
import org.csu.mall.common.UniformResponse;
import org.csu.mall.entity.Bank;
import org.csu.mall.entity.PayInfo;
import org.csu.mall.entity.User;
import org.csu.mall.persistence.BankMapper;
import org.csu.mall.persistence.PayInfoMapper;
import org.csu.mall.persistence.UserMapper;
import org.csu.mall.service.IUserService;
import org.csu.mall.utils.BigDecimalUtil;
import org.csu.mall.utils.MD5Util;
import org.csu.mall.utils.TokenCacheUtil;
import org.csu.mall.utils.UsernameUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PayServiceImpl payService;

    @Autowired
    private PayInfoMapper payInfoMapper;

    @Override
    public UniformResponse<User> login(String username, String password) {
//        QueryWrapper<User> query = new QueryWrapper<>();
//        query.eq("username", username);
        int rows = userMapper.selectCount(Wrappers.<User>query().eq("username",username));
        if(rows == 0){
            return UniformResponse.createForErrorMessage("用户名不存在");
        }
        String md5Passsword=MD5Util.md5Encrypt32Upper(password);
        User user = userMapper.selectOne(
                Wrappers.<User>query().eq("username",username).eq("password",md5Passsword));
        if(user == null){
            return UniformResponse.createForErrorMessage("用户名或密码错误");
        }
        user.setPassword(StringUtils.EMPTY);//密码不能返回给前端，需要置空
        UsernameUtil.setUsername("username",username);
        UsernameUtil.setUserId("userid",user.getId());
        System.out.println("user-shop:"+user.getShopId());
        return UniformResponse.createForSuccess("登录成功",user);
    }
    @Override
    public UniformResponse<String> checkUsername(){
        String username=UsernameUtil.getUsername("username");
        System.out.println("username:"+username);
        if(username==null){
            return UniformResponse.notLogining();
        }else{
            int rows = userMapper.selectCount(Wrappers.<User>query().eq("username",username));
            if (rows > 0 ){
                return UniformResponse.logining();
            }else {
                return UniformResponse.createForErrorMessage("用户名不存在");
            }
        }
    }
    @Override
    public UniformResponse<String> register(User user){
        UniformResponse<String> checkResponse = this.checkValid(user.getUsername(),CONSTANT.USERNAME);
        UniformResponse<String> checkResponseEmail = this.checkValid(user.getEmail(),CONSTANT.EMAIL);
        if(checkResponse.isSuccess()&&checkResponseEmail.isSuccess()){
            //用户名不存在
            user.setRole(CONSTANT.Role.CUSTOMER);
            user.setShopId(CONSTANT.SHOPID);
            user.setBalance(CONSTANT.BALANCE);
            //密码的MD5加密
            user.setPassword(MD5Util.md5Encrypt32Upper(user.getPassword()));
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());

            int rows = userMapper.insert(user);
            if (rows == 0) {
                return UniformResponse.createForErrorMessage("注册失败");
            }
            return UniformResponse.createForSuccessMessage("注册成功");

        }
        return UniformResponse.createForErrorMessage("用户名或邮箱已存在");
    }
    @Override
    public UniformResponse<String> checkValid(String value, String type){
        if(StringUtils.isNoneBlank(type)){
            if(CONSTANT.USERNAME.equals(type)){
                int rows = userMapper.selectCount(Wrappers.<User>query().eq("username",value));
                if (rows > 0 ){
                    return UniformResponse.createForErrorMessage("用户名已存在");
                }
            }
            if(CONSTANT.EMAIL.equals(type)){
                int rows = userMapper.selectCount(Wrappers.<User>query().eq("email",value));
                if (rows > 0 ){
                    return UniformResponse.createForErrorMessage("email已存在");
                }
            }
        }else{
            UniformResponse.createForErrorMessage("参数错误");
        }
        return UniformResponse.createForSuccessMessage("用户名和邮箱可用");
    }
    @Override
    public UniformResponse<User> getUserInfo(){
        String username=UsernameUtil.getUsername("username");
        UniformResponse<String> checkUsername = this.checkUsername();
        if(!checkUsername.isLogin()){
            //用户未登录
            return UniformResponse.notLogining();
        }
        User user = userMapper.selectOne(
                Wrappers.<User>query().eq("username",username));
        user.setPassword(StringUtils.EMPTY);//密码不能返回给前端，需要置空
        return UniformResponse.createForSuccess("用户信息查询成功",user);
    }
    @Override
    public UniformResponse<User> getUserInfoData(){
        String username=UsernameUtil.getUsername("username");
        UniformResponse<String> checkUsername = this.checkUsername();
        if(!checkUsername.isLogin()){
            //用户未登录
            return UniformResponse.notLogining();
        }
        User user = userMapper.selectOne(
                Wrappers.<User>query().eq("username",username));
        return UniformResponse.createForSuccess("用户信息查询成功",user);
    }
    @Override
    public UniformResponse<String> getForgetQuestion(String username){
        UniformResponse<String> checkResponse = this.checkValid(username,CONSTANT.USERNAME);
        if(checkResponse.isSuccess()){
            //用户名不存在
            return UniformResponse.createForErrorMessage("用户名不存在");
        }
        QueryWrapper<User> query = new QueryWrapper<>();
        query.select("question").eq("username",username);
        String question = userMapper.selectOne(query).getQuestion();
        if(StringUtils.isNotBlank(question)){
            return UniformResponse.createForSuccess("这是找回密码问题",question);
        }
        return UniformResponse.createForErrorMessage("该用户未设置找回密码问题");
    }
    @Override
    public UniformResponse<String> forgetCheckAnswer(String username, String question,String answer){
        UniformResponse<String> checkResponse = this.checkValid(username,CONSTANT.USERNAME);
        if(checkResponse.isSuccess()){
            //用户名不存在
            return UniformResponse.createForErrorMessage("用户名不存在");
        }
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username",username).eq("question",question).eq("answer",answer);
        int rows = userMapper.selectCount(query);
        if(rows > 0 ){
            //忘记密码的token生成和保存
            String forgetToken = UUID.randomUUID().toString();
            TokenCacheUtil.setToken("forgetToken",forgetToken);
            return UniformResponse.createForSuccess(forgetToken);
        }
        return UniformResponse.createForErrorMessage("找回密码的问题答案错误");
    }
    @Override
    public UniformResponse<String> forgetResetPassword(String username, String new_password,String forgetToken){
        UniformResponse<String> checkResponse = this.checkValid(username,CONSTANT.USERNAME);
        if(checkResponse.isSuccess()){
            //用户名不存在
            return UniformResponse.createForErrorMessage("用户名不存在");
        }
        if(forgetToken.equals(TokenCacheUtil.getToken("forgetToken"))){
            User user = userMapper.selectOne(Wrappers.<User>query().eq("username",username));
            user.setPassword(MD5Util.md5Encrypt32Upper(new_password));
            int rows = userMapper.updateById(user);
            if(rows == 0){
                return UniformResponse.createForErrorMessage("修改密码操作失效");
            }else {
                return UniformResponse.createForSuccessMessage("修改密码成功");
            }
        }else {
            return UniformResponse.createForErrorMessage("token已经失效");
        }
    }
    @Override
    public UniformResponse<String> resetPassword(String old_password, String new_password){
        User user = this.getUserInfoData().getData();//查询个人信息
        String md5_old_password=MD5Util.md5Encrypt32Upper(old_password);
        if (user.getPassword().equals(md5_old_password)){
            user.setPassword(MD5Util.md5Encrypt32Upper(new_password));
            user.setUpdateTime(LocalDateTime.now());
            int rows=userMapper.updateById(user);
            if(rows==0){
                return UniformResponse.createForSuccessMessage("修改密码失败");
            }
            return UniformResponse.createForSuccessMessage("修改密码成功");
        }else {
            return UniformResponse.createForErrorMessage("原密码输入错误");
        }
    }
    @Override
    public UniformResponse<User> updateInformation(User new_user) {
        User user = this.getUserInfoData().getData();//查询个人信息
        user.setPhone(new_user.getPhone());
        int rows = userMapper.selectCount(Wrappers.<User>query().eq("email",new_user.getEmail()));
        if(rows > 0 ){
            return UniformResponse.createForErrorMessage("邮箱已存在");
        }
        user.setEmail(new_user.getEmail());
        user.setUpdateTime(LocalDateTime.now());
        rows=userMapper.updateById(user);
        if(rows==0){
            return UniformResponse.createForErrorMessage("修改信息失败");
        }
        user.setPassword(StringUtils.EMPTY);
        return UniformResponse.createForSuccess("修改信息成功",user);
    }
    @Override
    public UniformResponse<String> logout(){
        User user = this.getUserInfoData().getData();//查询个人信息
        UsernameUtil.setUsername("username",StringUtils.EMPTY);
        System.out.println("登出");
        if(UsernameUtil.getUsername("username").isEmpty()){
            return UniformResponse.createForSuccessMessage("登出成功");
        }
        return UniformResponse.createForErrorMessage("登出失败");
    }

//    @Override
//    public UniformResponse<User> addBalance(BigDecimal balance) {
//        UniformResponse<String> checkUsername = this.checkUsername();
//        Integer userId=Integer.parseInt(UsernameUtil.getUsername("userid"));
//        if(!checkUsername.isLogin()){
//            //用户未登录
//            return UniformResponse.notLogining();
//        }
//        User user=userMapper.selectOne(Wrappers.<User>query().eq("id",userId));
////        Bank bank=bankMapper.selectById(bankId);
////        if(bank==null)
////        {
////            return UniformResponse.createForErrorMessage("用户没有添加银行卡或者银行卡已删除");
////        }
//        UniformResponse response=payService.payBalance(balance);
//        logger.info("余额充值中");
//        BigInteger orderNo=new BigInteger(String.valueOf(response.getData().toString()));
//        logger.info(String.valueOf(response.getData().toString()));
//
//        //todo 回调状态码来完成余额的充值
////        List<PayInfo> payInfoList=payInfoMapper.selectList(Wrappers.<PayInfo>query().eq("user_id",userId).eq("platform_status","TRADE_SUCCESS").orderByDesc("update_time"));
////        payInfoList.get(0);
//        user.setBalance(BigDecimalUtil.add(user.getBalance().doubleValue(),balance.doubleValue()));
//        user.setUpdateTime(LocalDateTime.now());
//        userMapper.updateById(user);
//        return UniformResponse.createForSuccess(user);
//    }
}
